# -*- coding: utf-8 -*-
import sys
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests,json
from common.helper import Helper
from urllib.parse import urlencode
class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "“悦享保”个人癌症医疗保障计划"
    def genProductInfo(self):
        plan = {
            # 年龄段
            "year":[str( i ) for i in range(45,81)],
            #有无社保
            "socialSec":["Y","N"],
            #保额
            "money":["2000000"],
            #恶性肿瘤医疗保赔
            "cancerMedical":["0","2000000"],
            #质子重离子医疗保额
            "extSerious":["0","1000000"],
            #投保免赔额
            "deductible":["0","10000"],
            #保障期限
            "expire":["1年"],
            #交费类型
            "payType":["年交"]
        }
        for v in product(plan["year"],plan["socialSec"],plan["money"],plan["cancerMedical"],plan["extSerious"],plan["deductible"],plan["expire"],plan["payType"]):
            data = Helper.formatProductInfo( plan, v )

            self.mysql.cursor.execute( domain[self.name]["insert_sql"].format(**data))
            self.mysql._conn.commit()
            print( domain[self.name]["insert_sql"].format(**data) )
    #执行爬虫
    def requestJson(self,dt=None,mysql=None):
        params = '''
        productCode: YXB_GRAZYLBZJH
        plan: planA
        enterAge: 45
        deductible: 10000
        socialSecurity: Y
        '''
        if dt["cancerMedical"] == "0" and dt["extSerious"] == "0":
            plan = "planA"
        elif dt["cancerMedical"] == "0" and dt["extSerious"] != "0":
            plan = "planB"
        elif dt["cancerMedical"] != "0" and dt["extSerious"] == "0":
            plan = "planC"
        elif dt["cancerMedical"] != "0" and dt["extSerious"] != "0":
            plan = "planD"

        data = Helper.perfectJson( params )
        data["enterAge"] = dt["year"]
        data["deductible"] = dt["deductible"]
        data["socialSecurity"] = dt["socialSec"]
        data["plan"] = plan
        print( data )
        payload = urlencode( data ).replace("+","")
        r = requests.get( url = domain[self.name]["url"] + payload,headers=domain[self.name]["header"])
        if r.status_code == 200 and r.text:
            price = Helper.decimalParse( r.json()["price"])
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            mysql.updatePrice( data )
        else:
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            mysql.updateTask( data )
            print("\n/*产品价格更新失败:%d*/"%dt["id"])
